package com.eportal.controller.background;

import com.alibaba.fastjson.JSONObject;
import com.eportal.action.background.FeeAlipayAuthAction;
import com.eportal.domain.Sysopt;
import com.eportal.entity.FeeAlipayAuthEntity;
import com.eportal.service.FeeAlipayAuthService;
import com.framework.jqgrid.Page;
import com.framework.jqgrid.PageEntity;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 支付宝授权管理
 * Created by Saber on 2017/8/22.
 */
@Controller
@RequestMapping(value = "/admin/feeAlipayAuth")
public class FeeAlipayAuthController {

    private static Logger logger = LoggerFactory.getLogger(FeeAlipayAuthController.class.getName());

    @Resource
    private FeeAlipayAuthService feeAlipayAuthService;

    /**
     * 支付宝授权管理列表
     * @author Saber
     * @Date 2017/8/22 下午6:41
     * @param request
     * @param pageEntity    分页对象
     * @param agtCode       合作方code
     * @see FeeAlipayAuthAction#page()
     * @return
     */
    @RequestMapping(value = "page.json")
    @ResponseBody
    public JSONObject page(HttpServletRequest request,PageEntity pageEntity,String agtCode){

        JSONObject json = new JSONObject();

        Sysopt user= (Sysopt)request.getSession().getAttribute("user");
        int userRole = (Integer)request.getSession().getAttribute("userRole");

        try {
            PageInfo<FeeAlipayAuthEntity> pageInfo=feeAlipayAuthService.queryForPage(agtCode,pageEntity,user,userRole);

            json.put("total",pageInfo.getTotal());

            if(pageInfo.getList().size()==0){
                json.put("msg","暂无数据");
            }else{
                json.put("msg","ok");
            }
            json.put("data",pageInfo.getList());
            Page page = new Page(pageInfo,pageEntity.getPageNo());
            json.put("page", page);
            json.put("code",1);
            return json;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("支付宝授权管理列表异常:",e);
            json.put("code", 0);
            json.put("msg","服务器发生异常:"+e.getMessage());
            json.put("data",null);
            return json;
        }
    }

    /**
     * 支付宝授权添加
     * @author Saber
     * @Date 2017/8/23 上午9:58
     * @param request
     * @param entity        对象
     * @see FeeAlipayAuthAction#add()
     * @return
     */
    @RequestMapping(value = "add.json",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject add(HttpServletRequest request,FeeAlipayAuthEntity entity){
        JSONObject json = new JSONObject();

        Sysopt user= (Sysopt)request.getSession().getAttribute("user");
        int userRole = (Integer)request.getSession().getAttribute("userRole");

        try {
            json = feeAlipayAuthService.add(entity, user, userRole);
            return json;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("支付宝授权添加异常:",e);
            json.put("code",0);
            json.put("msg","服务器发生异常:"+e.getMessage());
            json.put("data",null);
            return json;
        }
    }


    /**
     * 支付宝授权详情
     * @author Saber
     * @Date 2017/8/23 下午1:07
     * @param sid   sId 主键
     * @see FeeAlipayAuthAction#editView()
     * @return
     */
    @RequestMapping(value = "detail.json")
    @ResponseBody
    public JSONObject detail(Long sid){
        JSONObject json = new JSONObject();

        try {
            FeeAlipayAuthEntity entity = feeAlipayAuthService.findByPrimaryKey(sid);
            json.put("code",1);
            json.put("msg","ok");
            json.put("data",entity);
            return json;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("支付宝授权详情异常:",e);
            json.put("code",0);
            json.put("msg","服务器发生异常:"+e.getMessage());
            json.put("data",null);
            return json;
        }
    }

    /**
     * 支付宝授权修改
     * @author Saber
     * @Date 2017/8/23 下午1:15
     * @param request
     * @param entity        对象 sid非空
     * @return
     */
    @RequestMapping(value = "update.json",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject update(HttpServletRequest request,FeeAlipayAuthEntity entity){
        JSONObject json = new JSONObject();

        Sysopt user= (Sysopt)request.getSession().getAttribute("user");
        int userRole = (Integer)request.getSession().getAttribute("userRole");

        try {
            json= feeAlipayAuthService.update(entity, user, userRole);
            return json;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("支付宝授权详情异常:",e);
            json.put("code",0);
            json.put("msg","服务器发生异常:"+e.getMessage());
            json.put("data",null);
            return json;
        }
    }

    /**
     * 支付宝授权删除
     * @author Saber
     * @Date 2017/8/23 下午2:54
     * @param request
     * @param sids      sid集合 用,分割
     * @see FeeAlipayAuthAction#delete()
     * @return
     */
    @RequestMapping(value = "delete.json")
    @ResponseBody
    public JSONObject delete(HttpServletRequest request,String sids){
        JSONObject json = new JSONObject();

        try {
            String[] ids = sids.split(",");
            for (String sid : ids) {
                feeAlipayAuthService.delete(sid);
            }
            json.put("code",1);
            json.put("msg","删除成功");
            json.put("data",ids.length);
            return json;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("支付宝授权删除异常:",e);
            json.put("code",0);
            json.put("msg","服务器发生异常:"+e.getMessage());
            json.put("data",null);
            return json;
        }
    }

    /**
     * 支付宝授权回调页面（支付宝调用）  改方法的启用与否取决于 FeeAlipayAuthServiceImpl.getUrl()方法中的配置
     * @author Saber
     * @Date 2017/8/23 下午1:07
     * @param request
     * @param app_auth_code 授权码
     * @param app_id
     * @param sid
     * @see FeeAlipayAuthAction#feeAlipayAuthView()
     * @see com.eportal.service.impl.FeeAlipayAuthServiceImpl#getUrl(Long)
     * @return
     */
    @RequestMapping(value = "feeAlipayAuth.json")
    public String feeAlipayAuth(HttpServletRequest request,String app_auth_code,String app_id,Long sid){
        JSONObject json = new JSONObject();
        try {

            if (StringUtils.isBlank(app_id) || StringUtils.isBlank(app_auth_code)) {
                request.setAttribute("code", 0);
            }else{
                //使用app_auth_code换取app_auth_token
                json = feeAlipayAuthService.codeChangeToken(sid, app_id, app_auth_code);
            }
            logger.info("支付宝授权回调结果:", json.get("msg"));
            if(!"1".equals(json.get("code").toString())){

            }else{
                json.put("code", 1);
                json.put("msg", "获取支付宝授权信息成功");
            }
            request.setAttribute("result", json);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("支付宝授权回调异常",e);
        }
        return "sysmanage/feeAlipayAuth/feeAlipayAuthView";
    }










}
